<?php
namespace App\Libs;

use \GatewayWorker\Lib\Gateway;
use Swoole\JS;

class Chats{
    protected $db;
    protected $prefix;
    protected $redis;
    protected $utility;
    protected $Chat;

    public function __construct($db, $redis, $utility)
    {
        $this->db = $db;
        $this->redis = $redis;
        $this->utility = $utility;
        $this->Chat = \jsonRpcClient::instance('Chat');
    }
    public function chatMessage($client_id, $paras){
        //组装预备要访问的函数(过程)名
        $func = 'cmd_'.$paras['cmd'];

        if (method_exists($this, $func))
        {
            $this->$func($client_id, $paras);
        }else{
            Gateway::sendToCurrentClient(json_encode(array(
                'state' => 404,
                'msgid' => 404,
            )));
            Gateway::closeClient($client_id);
        }
    }

    public function cmd_pong($client_id, $paras)
    {
        if(isset($_SESSION['room_id'])) {
            $room_id = $_SESSION['room_id'];
            $result = array(
                'cmd' => 'pong',
                'room_online' => Gateway::getClientCountByGroup($room_id),
            );
        }else{
            $result = array(
                'cmd' => 'pong',
            );
        }
        Gateway::sendToCurrentClient(json_encode($result));
    }
    /**
     * 列出聊天室
     * @param $client_id
     * @param $paras
     */
	public function cmd_chatroomslist($client_id, $paras)
    {
        $result = array('state'=>200,'cmd'=>$paras['cmd']);
        //从库中取出房间数据
        $rooms = $this->Chat->roomslist();
        if($rooms['state']==200){
            $result['rooms'] = $rooms['data']['rooms'];
            $result['online'] = $rooms['data']['online'];
        }else{
            $result['state'] = 404;
            $result['msgid'] = 10028;
        }
        Gateway::sendToCurrentClient(json_encode($result));
        Gateway::closeClient($client_id);
    }

    /**
     * 检测房间的类型，并返回房间的参数
     * @param $client_id
     * @param $paras
     */
    public function cmd_checkroomtype($client_id, $paras)
    {
        //$result = array('state'=>404, 'cmd'=>$paras['cmd']);
        $data = $this->Chat->checkRoomType($paras);
        $result = $data['data'];

        //print_r($result);

        if($result['state']!=200){
            return Gateway::sendToCurrentClient(json_encode($result));
        }
        //在线人数
        $roomOnline = Gateway::getClientCountByGroup($result['roomid']) + 1;

        // 获取房间内所有用户列表
        $room_userlist = array();
        $room_clientlist = Gateway::getClientSessionsByGroup($result['roomid']);
        foreach($room_clientlist as $item)
        {
            $room_userlist[$item['uno']] = $item['nickname'];
        }
        //$room_userlist[$result['roomuser']['uno']] = $result['roomuser']['nickname'];
        # 推送给当前聊天室的所有人员
        $result['pushgroup']['room_online'] = $roomOnline;
        Gateway::sendToGroup($result['roomid'], json_encode($result['pushgroup']));
        //加入房间
        Gateway::joinGroup($client_id, $result['roomid']);
        $_SESSION['uno'] = $result['roomuser']['uno'];
        $_SESSION['room_id'] = $result['roomid'];
        $_SESSION['nickname'] = $result['roomuser']['nickname'];
        $_SESSION['avatar'] = $result['roomuser']['avatar'];
        Gateway::bindUid($client_id, $result['roomuser']['uno']);
        //Gateway::bindUid($client_id, $result['roomuser']['uid']);
        # 推送给自己
        unset($result['pushgroup']);
        $result['room_online'] = $roomOnline;
        $result['room_userlist'] = $room_userlist;
        Gateway::sendToCurrentClient(json_encode($result));
        /*
        $room_id = $this->utility->existsKeyInArray('room_id', $paras, 'S');
        $token = $this->utility->existsKeyInArray('token', $paras, 'S');
        $nickname = $this->utility->existsKeyInArray('nickname', $paras, 'S', '');
        $uno = '';
        if(empty($room_id)){
            $result['msgid'] = 10031;
            return Gateway::sendToCurrentClient(json_encode($result));
        }
        $room_autoid = str_replace('chat_', '', $room_id);
        $data = $this->db->row("SELECT * FROM `rp_rooms` WHERE `id`=".intval($room_autoid)." AND `state`=1");
        if(!$data)
        {
            $result['msgid'] = 10031;
            return Gateway::sendToCurrentClient(json_encode($result));
        }
        $user = array(
            'uno' => 'S'.$this->utility->makeUserNo($this->db),
            'usertype' => 0,
            'nickname' => '',
            'usercoin' => 0,
            'avatar' => 'no',
        );
        $user['nickname'] = empty($nickname) ? '游客S'.$user['uno'] : $nickname;
        $userToken['state'] = 404;
        if(!empty($token)) $userToken = $this->utility->exitsToKen($client_id, $paras, false);
        if($userToken['state']==200){
            $user = $userToken;
        }
        if(intval($data['roomtype'])==1 && intval($user['usertype'])==0)
        {
            if($user['state']!=200)
            {
                $result['msgid'] = 10032;
                return Gateway::sendToCurrentClient(json_encode($result));
            }
        }
        $uno = $user['uno'];
        //拉取黑名单
        $isBlackUser = true;
        $blacklist = $this->utility->chatBlacklist($this->redis, $this->db, $room_id);
        $isBlackUser = $this->utility->existsBlackUser($uno, $blacklist);
        if($isBlackUser){
            //黑名单直接断开连接
            Gateway::sendToCurrentClient(json_encode(array(
                'msgid' => 10035,
                'state' => 404,
                'cmd' => $paras['cmd'],
            )));
            Gateway::leaveGroup($client_id, $room_id);
            Gateway::closeCurrentClient();
            return;
        }
        //通知所有在房间的玩家
        //在线人数是当前总数+1，后面自己再加入
        $room_online = Gateway::getClientCountByGroup($room_id) + 1;
        $group_result = array(
            'cmd' => 'newuserjoin',
            'state' => 200,
            'nickname' =>  $user['nickname'],
            'useruno' => $user['uno'],
            'room_online' => $room_online,
            'time'=>$this->utility->formatTimes(time()),
        );
        Gateway::sendToGroup($room_id, json_encode($group_result));
        //加入房间
        Gateway::joinGroup($client_id, $room_id);
        $_SESSION['uno'] = $user['uno'];
        $_SESSION['room_id'] = $room_id;
        $_SESSION['nickname'] = $user['nickname'];
        $_SESSION['avatar'] = $user['avatar'];
        Gateway::bindUid($client_id, $_SESSION['uno']);

        // 获取房间内所有用户列表
        $room_userlist = array();
        $room_clientlist = Gateway::getClientSessionsByGroup($room_id);
        foreach($room_clientlist as $item)
        {
            $room_userlist[$item['uno']] = $item['nickname'];
        }
        $room_userlist[$user['uno']] = $user['nickname'];

        unset($user['uid']);
        unset($user['state']);
        unset($user['token']);
        $result['state'] = 200;
        $result['datas'] = $data;
        $result['roomuser'] = $user;
        $result['room_online'] = $room_online;
        $result['room_userlist'] = $room_userlist;
        Gateway::sendToCurrentClient(json_encode($result));
        */
    }

    public function cmd_say($client_id, $paras)
    {
        $result = array('state'=>404, 'cmd'=>$paras['cmd']);

        if(!isset($_SESSION['uno']))
        {
            $result['msgid'] = 301;
            return Gateway::sendToCurrentClient(json_encode($result));
        }
        // 非法请求
        if(!isset($_SESSION['room_id']))
        {
            throw new \Exception("\$_SESSION['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']}");
        }

        $paras['cmd'] = $paras['cmd'];
        $paras['uno'] = $_SESSION['uno'];
        $paras['avatar'] = $_SESSION['avatar'];
        $paras['nickname'] = $_SESSION['nickname'];
        $paras['room_id'] = $_SESSION['room_id'];
        $paras['lastSayTimes'] = (isset($_SESSION['lastSayTimes']) ? $_SESSION['lastSayTimes'] : 0);

        $data = $this->Chat->roomSay($paras);
        $result = $data['data'];
        //print_r($result);
        $saystate = $result['saystate'];
        unset($result['saystate']);
        if($result['state']==200)
        {
            switch ($saystate) {
                case 200:
                    //记录最后发言的时间
                    $_SESSION['lastSayTimes'] = time();
                    return Gateway::sendToGroup($paras['room_id'] ,json_encode($result));
                    break;
                case 304: // 私聊
                    Gateway::sendToCurrentClient(json_encode($result));
                    unset($data['content']);
                    //Gateway::sendToGroup($paras['room_id'], json_encode($result));
                    return Gateway::sendToUid($paras['to_uno'], json_encode($result));
                    break;
                case 303: //禁言状态
                    return Gateway::sendToCurrentClient(json_encode($result));
                    break;
                case 302: //太快
                    return Gateway::sendToCurrentClient(json_encode($result));
                    break;
                case 301: //黑名单
                    Gateway::leaveGroup($client_id, $paras['room_id']);
                    Gateway::closeCurrentClient();
                    return $data;
                    break;
            }

        }else{
            return $result;
        }
    }

    /**
     * 发红包
     * @param $client_id
     * @param $paras
     * @return bool
     */
    public function cmd_send_red_envelopes($client_id, $paras)
    {
        $paras['remoteip'] = bindec(decbin(ip2long($_SERVER['REMOTE_ADDR'])));
        $data = $this->Chat->sendRedEnvelopes($paras);
        $result = $data['data'];
        $result['cmd'] = $paras['cmd'];
        if($result['state']==200){
            $updatecoin = array(
                'cmd' => 'updatecoin',
                'state' => 200,
                'usercoin' => $result['usercoin'],
            );
            Gateway::sendToCurrentClient(json_encode($updatecoin));
            unset($result['usercoin']);
            return Gateway::sendToGroup($result['room_id'], json_encode($result));
        }else{
            return Gateway::sendToCurrentClient(json_encode($result));
            //return Gateway::sendToGroup($_SESSION['room_id'], json_encode($result));
        }
    }

    /**
     * 抢红包
     * @param $client_id
     * @param $paras
     */
    public function cmd_chat_grab_red($client_id, $paras)
    {
        $paras['remoteip'] = bindec(decbin(ip2long($_SERVER['REMOTE_ADDR'])));
        $data = $this->Chat->gradRedEnvelopes($paras);
        $result = $data['data'];
        //print_r($result);
        if($result['state']==200){
            Gateway::sendToGroup($result['room_id'], json_encode($result['groupmsg']));
            unset($result['groupmsg']);
            return Gateway::sendToCurrentClient(json_encode($result));
        }else{
            return Gateway::sendToCurrentClient(json_encode($result));
        }
    }
}